<?php

namespace app\api\controller\app;

use addons\epay\library\Service;
use app\admin\model\Article;
use app\admin\model\Articletype;
use app\admin\model\City;
use app\admin\model\Shop;
use app\admin\model\Shopcharge;
use app\admin\model\Shopchargeconfig;
use app\admin\model\Shopdevice;
use app\admin\model\Shopjoin;
use app\admin\model\Shoporder;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoproombook;
use app\admin\model\Shoproomset;
use app\admin\model\Shoptuan;
use app\admin\model\Tuanorder;
use app\admin\model\Userbalance;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\admin\model\Userweixin;
use app\api\service\DeviceService;
use app\api\service\RoomService;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Http;
use fast\Random;
use think\Config;
use think\Validate;
use Yansongda\Pay\Pay;

/**
 *
 */
class Scan extends Api
{
    protected $noNeedLogin = ['wechatNotify'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

    }


    /**
     * 扫码获取店铺信息和房间信息
     */
    public function hourList(){

        $shop_id = $this->request->param('shop_id');
        $room_id = $this->request->param('room_id');

        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id',$room_id)->find();
        $minHour = $room['min_book_hour'];
        $ret = array();
        $shopDeviceModel = new Shopdevice();
        for ($i=0;$i<=3;$i++){
            $obj = array();
            $obj['hour'] = $i+$minHour;
            $obj['price'] = round(($i+$minHour)*$room['hour_price'],2);

            $ret[] = $obj;
        }
        $this->success('',$ret);
    }


    public function addOrder(){

        /**
         * 订购今天得
         */
        $id = $this->request->param('id');
        $date = date("Y-m-d",time());
        $startTime = date("H:i",time());
        $hour = $this->request->param('hour');
        $setId = -1;


        /**
         * 判断是和已预定的时间冲突
         */
        $time1 = strtotime($date." ".$startTime);

        $min = $hour*60;

        $endTime = strtotime("+" . $min . " minute", strtotime($date . " " . $startTime));

        $time2 = $endTime;
        $shopRoomBookModel = new Shoproombook();
        $checkStart = $shopRoomBookModel->where('room_id',$id)->where('start_time',"<=",$time1)->where("end_time",">=",$time1)->find();
        $checkEnd = $shopRoomBookModel->where('room_id',$id)->where('start_time',"<=",$time2)->where("end_time",">=",$time2)->find();

        if($checkStart != null || $checkEnd != null){
            $this->error("此时间段预被预定");
        }
        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id',$id)->find();
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id',$room['shop_id'])->find();
        if($setId == -1){
            $totalPrice = $hour* $room['hour_price'];
        }else{
            $shopRoomBookSetModel = new Shoproomset();
            $set  = $shopRoomBookSetModel->where('room_id',$id);
            $totalPrice = $set['amount'];
        }
        $user = $this->auth->getUser();
        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($room['shop_id'],$user['id']);

        $pay_price = $totalPrice;
        $type = "";
        $dis_price = 0 ;
        if($balance > 0){
            $type = "balance";
            if($balance >= $totalPrice){
                $dis_price = $totalPrice;
                $pay_price = 0;
            }else{
                $dis_price = $balance;
                $pay_price = $totalPrice-$balance;
            }

        }

        $orderNo = getOrderSn();
        $db = array();
        $db['shop_id'] = $shop['id'];
        $db['shop_name'] = $shop['name'];
        $db['room_id'] = $room['id'];
        $db['room_name'] = $room['name'];
        $db['user_id'] = $user['id'];
        $db['order_no'] = $orderNo;
        $db['create_time'] = time();
        $db['update_time'] = time();
        $db['amount'] = $totalPrice;
        $db['pay_amount'] = $pay_price;
        $db['book_start'] = $time1;
        $db['book_end'] = $time2;
        $db['set_id'] = $setId;
        $db['balance'] = $dis_price;
        $code = mt_rand(100000, 999999);
        $db['open_code'] =$code;


        $shopOrderModel = new Shoporder();
        $id = $shopOrderModel->insertGetId($db);
        if($id>0){

            $info = array();
            if($pay_price >0){
                $userwxModel = new Userweixin();
                $wx = $userwxModel->where('user_id', $user['id'])->find();
                $params = [
                    'out_trade_no' => $orderNo,//你的订单号
                    'total_fee' => $pay_price * 100,//单位元
                    'body' => $shop['name'] . "预定".$hour."小时",
                    'openid' => $wx['openid'],

                ];
                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/scan/wechatNotify";
                $config = Service::getConfig("wechat");
                $config['notify_url'] = $url;
                $pay = Pay::wechat($config);
                $result = $pay->miniapp($params);

                $info['order_no'] = $orderNo;
                $info['payInfo'] = json_decode($result, true);
            }else{


                $info['order_no'] = $orderNo;
                $info['payInfo'] = "";

                $info['order_no'] = $orderNo;
                $info['payInfo'] = "";
                $shopOrderModel->where('id',$id)->update(['status'=>'payed','update_time'=>time()]);

                $deviceService = new DeviceService();
                $order = $shopOrderModel->where('id',$id)->find();
                $this->redis->set($order['shop_id'], time());
                $roomService = new RoomService();
                $bookModel = new Shoproombook();
                $roomService->addBookData($order);
                $book = $bookModel->where('order_id',$order['id'])->find();

                $deviceService->openRoom($book,$order['user_id'],$this->openCmdUrl);

            }

            if($type == "balance"){

                $userBalanceModel = new Userbalance();
                $userBalanceModel->insert(['user_id'=>$user['id'],'type'=>'out',
                    'amount'=>-$dis_price,'mark'=>$shop['name'].'预定抵扣','create_time'=>time(),'shop_id'=>$shop['id'],'order_id'=>$id]);
            }

            $this->success('下单成功', $info);
        }else{
            $this->error("订单生成失败,请联系客服");
        }

    }


    public function wechatNotify(){

        $config = Service::getConfig('wechat');
        $pay = Pay::wechat($config);
        $result = $pay->verify();

        $out_trade_no = $result['out_trade_no'];
        $amount = $result['total_fee'] / 100;


        if (in_array($result['return_code'], ['SUCCESS'])) {


            $shopOrderModel = new Shoporder();
            $order = $shopOrderModel->where('order_no', $out_trade_no)->find();
            $shopOrderModel->where('id',$order['id'])->update(['status'=>'payed','update_time'=>time()]);


            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id',$order['shop_id'])->find();

            /**
             * 商家分润
             */
            $shopOrderProfitModel  = new Shoporderprofit();
            $shopOrderProfitModel->insert(['order_id'=>$order['id'],'shop_id'=>$order['shop_id'],'type'=>'order',
                'user_id'=>$shop['user_id'],'create_time'=>time(),'amount'=>formatMoney(($order['pay_amount']-$order['rate']-$order['pay_rate']))]);


            $shopAgentProfitModel = new Userorderprofit();

            /**
             * 代理商分润
             */
            if($shop['agent_ratio'] > 0){

                $agentFee = $shop['agent_ratio']*$order['pay_amount']/100;
                $shopAgentProfitModel->insert(['order_id'=>$order['id'],'shop_id'=>$order['shop_id'],'type'=>'order',
                    'user_id'=>$shop['agent_id'],'create_time'=>time(),'amount'=>formatMoney($agentFee)]);
            }


            $this->redis->set($order['shop_id'], time());

            $bookModel = new Shoproombook();
            $deviceService = new DeviceService();

            $roomService = new RoomService();
            $roomService->addBookData($order);

            $book = $bookModel->where('order_id',$order['id'])->find();

            $deviceService->openRoom($book,$order['user_id'],$this->openCmdUrl);


        }
        return $pay->success();
    }



}
